package team.lhc.cms.mapper;

import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Options;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import org.springframework.stereotype.Repository;
import team.lhc.cms.dto.UserDTO;
import team.lhc.cms.entity.User;

import java.util.List;

/**
 * @author 文
 * @description user的数据持久层
 */
@Repository
public interface UserMapper {

    /**
     * 根据username查找用户
     * @author 文
     * @param username
     * @return
     */
    @Select("select * from user where username=#{username}")
    User findByUsername(String username);

    /**
     * 保存用户
     * @author 文
     * @param user
     * @return
     */
    @Insert("INSERT INTO `user` (`userName`, `password`, `role`, `isLocked`,`openid`) VALUES ( #{username}, #{password}, #{role}, #{isLocked}, #{openid})")
    @Options(useGeneratedKeys=true, keyProperty="uid", keyColumn="uid")
    void save(User user);

    /**
     * 根据openid查找用户
     * @author 文
     * @param openid
     * @return
     */
    @Select("select * from user where openid=#{openid}")
    User findByOpenId(String openid);

    /**
     * 根据openid锁定账户
     * @author 文
     * @param openid
     */
    @Update("UPDATE `user` SET `isLocked`= 1 WHERE (`openid`=#{openid})")
    void updateIsLockByOpenid(String openid);

    /**
     * 根据openid更新用户名和角色
     * @author 文
     * @param openid
     * @param phoneNumber
     * @param role
     */
    @Update("UPDATE `user` SET `username`=#{phoneNumber}, `role`=#{role} WHERE (`openid`=#{openid})")
    void updateUsernameAndRoleByOpenid(String openid, String phoneNumber, String role);

    /**
     * 根据uid更新用户名和角色
     * @author 文
     * @param nickName
     * @param roleInfo
     * @param uid
     */
    @Update("UPDATE `user` SET `username`=#{nickName}, `role`=#{roleInfo} WHERE (`uid`=#{uid})")
    void updateUsernameAndRoleByUid(String nickName, String roleInfo, Integer uid);

    /**
     * 根据uid锁定账户
     * @author 文
     * @param uid
     */
    @Update("UPDATE `user` SET `isLocked`= 1 WHERE (`uid`=#{uid})")
    void updateIsLockByUid(Integer uid);

    /**
     * 根据uid获得用户信息
     * @author 文
     * @param uid
     * @return
     */
    @Select("select * from user where uid = #{uid}")
    User findByUid(Integer uid);

    /**
     * 根据uid设置role为空
     * @author 文
     * @param uid
     * @return
     */
    @Update("UPDATE `user` SET `role`= NULL WHERE (`uid`=#{uid})")
    int setRoleNullByUid(Integer uid);

    /**
     * 获取用户信息
     * @author 文
     * @return
     */
    @Select("select uid,username,role,isLocked from user")
    List<UserDTO> getList();

    /**
     * 更新用户信息
     * @author 文
     * @param userDTO
     * @return
     */
    @Update("UPDATE `user` SET `username`=#{username}, `isLocked`=#{isLocked} WHERE (`uid`=#{uid})")
    Integer update(UserDTO userDTO);
}
